package jmine.tec.web.servlet.rest.subscription;

import javax.servlet.http.HttpServletRequest;

import jmine.tec.subscription.SubscriptionManager;
import jmine.tec.subscription.SubscriptionSet;

/**
 * Classe para auxiliar servlets que queiram interagir com o {@link SubscriptionManager}
 * 
 * @author takeshi
 */
public class SubscriptionServletSupport {

    private SubscriptionManager subscriptionManager;

    public static final String TOKEN_KEY_NAME = SubscriptionServletSupport.class + "->token";

    /**
     * @return the subscriptionManager
     */
    public SubscriptionManager getSubscriptionManager() {
        return this.subscriptionManager;
    }

    /**
     * @param subscriptionManager the subscriptionManager to set
     */
    public void setSubscriptionManager(SubscriptionManager subscriptionManager) {
        this.subscriptionManager = subscriptionManager;
    }

    /**
     * Devolve o {@link SubscriptionSet} na session ou <code>null</code> se nenhum estiver presente
     * 
     * @param request {@link HttpServletRequest}
     * @return {@link SubscriptionSet}
     */
    public SubscriptionSet getSubscriptionSet(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(TOKEN_KEY_NAME);
        if (attribute == null) {
            return null;
        }
        return this.getSubscriptionManager().getSubscriptionSet((Long) attribute);
    }

    /**
     * Pega o {@link SubscriptionSet} ou cria um novo
     * 
     * @param request o {@link HttpServletRequest}
     * @return {@link SubscriptionSet}
     */
    public SubscriptionSet getOrCreateSubscriptionSet(HttpServletRequest request) {
        SubscriptionSet set2 = this.getSubscriptionSet(request);
        if (set2 == null) {
            set2 = this.getSubscriptionManager().newSubscription();
            request.getSession().setAttribute(TOKEN_KEY_NAME, set2.getToken());
        }
        return set2;
    }

    /**
     * Cancela uma subscription
     * 
     * @param request {@link HttpServletRequest}
     */
    public void cancelSubscription(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(TOKEN_KEY_NAME);
        if (attribute == null) {
            return;
        }
        SubscriptionSet set = this.getSubscriptionManager().getSubscriptionSet((Long) attribute);
        this.getSubscriptionManager().cancelSubscription(set);
    }

}
